'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 1. 添加fullName字段（如果不存在）
      const tableDescription = await queryInterface.describeTable('users');
      
      if (!tableDescription.fullName) {
        await queryInterface.addColumn('users', 'fullName', {
          type: Sequelize.STRING(100),
          allowNull: true,
        }, { transaction });
      }
      
      // 2. 更新现有的'inactive'和'suspended'状态为'disabled'
      await queryInterface.sequelize.query(
        "UPDATE users SET status = 'disabled' WHERE status IN ('inactive', 'suspended')",
        { transaction }
      );
      
      // 3. 修改name字段允许为空
      await queryInterface.changeColumn('users', 'name', {
        type: Sequelize.STRING(100),
        allowNull: true,
      }, { transaction });
      
      // 4. 为没有name的用户设置name字段
      await queryInterface.sequelize.query(
        "UPDATE users SET name = COALESCE(fullName, username) WHERE name IS NULL OR name = ''",
        { transaction }
      );
      
      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  },

  async down(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 恢复操作
      if (await queryInterface.describeTable('users').fullName) {
        await queryInterface.removeColumn('users', 'fullName', { transaction });
      }
      
      await queryInterface.changeColumn('users', 'name', {
        type: Sequelize.STRING(100),
        allowNull: false,
      }, { transaction });
      
      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}; 